package com.school.edupoint.msg;

import com.school.edupoint.service.ActivityService;
import com.school.edupoint.model.Activity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ActivityTask {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 每分钟执行一次预热任务
    @Scheduled(cron = "0 * * * * ?")
    public void warmUpActivities() {
        LocalDateTime now = LocalDateTime.now();
        // 创建时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        List<Activity> activities = activityService.getActivitiesStartingSoon(now);

        if (activities.isEmpty()) {
            System.out.println("未找到需要预热的活动");
            return;
        }

        for (Activity activity : activities) {
            try {
                // 正确解析结束时间
                LocalDateTime endTime = LocalDateTime.parse(activity.getActivityEndTime(), formatter);

                // 计算TTL（秒）
                long ttlSeconds = Duration.between(now, endTime).getSeconds();
                if (ttlSeconds < 0) ttlSeconds = 1; // 活动已结束

                // 1. 存储活动信息
                String activityKey = "activity:info:" + activity.getId();
                redisTemplate.opsForValue().set(activityKey, activity, ttlSeconds, TimeUnit.SECONDS); // 单位修正

                // 2. 令牌桶
                String tokenKey = "activity:tokens:" + activity.getId();
//                int availableSlots = activity.getHeadCount() - (activity.getReg() != null ? activity.getReg() : 0);
                int availableSlots = activity.getHeadCount();
                System.out.println("activity.getHeadCount()" + activity.getHeadCount());
                System.out.println("availableSlots)" + availableSlots);
                Set<String> tokenSet = new HashSet<>();


                for (int i = 0; i < availableSlots; i++) {
                    System.out.println("正在生成第 " + (i+1) + " 个 token");
                    String token = UUID.randomUUID().toString();
                    String tokenDetailKey = "activity:tokens:" + activity.getId() + ":token:" + token;
                    System.out.println("生成的token为" + token);
                    
                    try {
                        // 存储token详情
                        stringRedisTemplate.opsForValue().set(tokenDetailKey, token, ttlSeconds, TimeUnit.SECONDS);
                        System.out.println("成功存储token详情: " + tokenDetailKey);
                        
                        // 将token添加到Set中
                        Long addResult = redisTemplate.opsForSet().add(tokenKey, token);
                        System.out.println("添加token到Set结果: " + addResult + ", token: " + token);
                        
                        // 验证token是否成功添加到Set中
                        Boolean isMember = redisTemplate.opsForSet().isMember(tokenKey, token);
                        System.out.println("验证token是否在Set中: " + isMember);
                        
                        // 获取当前Set的大小
                        Long setSize = redisTemplate.opsForSet().size(tokenKey);
                        System.out.println("当前Set大小: " + setSize);
                    } catch (Exception e) {
                        System.err.println("存储token时发生错误: " + e.getMessage());
                        e.printStackTrace();
                    }
                }
                
                // 设置token集合的过期时间
                redisTemplate.expire(tokenKey, ttlSeconds, TimeUnit.SECONDS);
                
                // 最终验证
                Long finalSetSize = redisTemplate.opsForSet().size(tokenKey);
                System.out.println("最终Set大小: " + finalSetSize);

                // 3. 活动状态
                String statusKey = "activity:status:" + activity.getId();
                redisTemplate.opsForValue().set(statusKey, 1, ttlSeconds, TimeUnit.SECONDS); // 单位修正
//更新活动状态
                activityService.updateStatusById(activity.getId());
                System.out.println("预热活动[" + activity.getTitle() +
                        "], 结束时间: " + endTime +
                        ", TTL: " + ttlSeconds + "秒");
            } catch (Exception e) {
                System.err.println("处理活动[" + activity.getId() + "]出错: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}